﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SQLServerHealthCheck.Model;
using AG.Utilities;

namespace SQLServerHealthCheck.SQLServer.IssueTypes
{
    public class DatabaseCheckTooLittleRelations : IssueTypeCheckBase
    {
        public DatabaseCheckTooLittleRelations()
        {
            IssueTypeId = 3018;
        }

        public override void Check()
        {
            try
            {
                // Create a Data Context 
                HealthCheckDataContext dc = new HealthCheckDataContext(System.Configuration.ConfigurationManager.AppSettings["ConnectionStringSSHCDatabase"]);
                Issue issue;

                ThresholdValue percentage = dc.ThresholdValues.FirstOrDefault(t => t.IssueTypeID == IssueTypeId && t.ThresholdValueID == 1);
                
                // Create a link Query ( query Selects a database that has the MDF file stored on the C Drive 
                var qry = from d in dc.Databases
                          where d.SourceDatabaseId == null
                          orderby d.DatabaseName
                          select new
                          {
                              DatabaseID = d.DatabaseID,
                              name = d.DatabaseName,
                              tables = d.Tables.Count(),
                             relations = (
                                            from t in d.Tables
                                           from r in t.Relations
                                            
                                            select r.RelationID).Count(),
                         


                          };
         


                foreach (var database in qry)
                {
                    int databaseId = database.DatabaseID;
                    //Get Issuetype object
                    if (database.relations < ((percentage.Value / 100) * database.tables))
                    {
                        issue = new Issue();

                        //Get Issuetype object  And Create a new  Global issue object 
                        IssueType issueType = dc.IssueTypes.FirstOrDefault(i => i.IssueTypeId == IssueTypeId);

                        issue.IssueType = issueType;
                        issue.TargetId = database.DatabaseID;
                        issue.Description = issueType.Description.Replace("{Database}", database.name);

                        dc.Issues.InsertOnSubmit(issue);
                    }
                }

                dc.SubmitChanges();

            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }



    }
}
